// index.js
import { ArrayToHeavy } from '../../utils/index.js'
import { SearchModel } from '../../models/search'
const ModelSearch = new SearchModel()
const App = getApp()

Page({
  data: {
    statusBarHeight: App.globalData.statusBarHeight, //顶部导航栏高度
    isTabbar: false, //是不是主页面
    searchText: '', //输入的搜索内容
    autoFocus: true, //搜索框自动聚焦
    historyList: [], //历史搜索记录
    hotList: [], //热门搜索记录
    recordShow: true, //展示历史搜索记录和热搜
    SearchInfoShow: false, //展示搜索结果
    showSearch: true, //是否显示顶部搜索框
    pageIndex: 1,
    pageSize: 20,
    loading: false,
    hasNext: true,
    searchInfo: {}, //搜索结果
    isShowHistory: false, //展开搜索记录
    historyHeight: '', //历史记录最大高度
    packUpHistory: false, //收起历史搜索记录
    showMoreActivity: false, //展开更多专场
    priceState: 0, //搜索条件-价格状态
    discountState: 0, //搜索条件-折扣状态
    screeningState: 0, //搜索条件-筛选
    empty: false, //搜索内容是否为空
    sort: '', //搜索条件
    isBack: false, //是否筛选过
    mallType: '', //商品类型
    brand: '', //品牌id
    selected: [], //筛选记录
    type: '', //是否从分类或者商品详情点击进来
    scrollTop: '', //页面滑动距离
    fixTop: '', //筛选栏距离顶部高度
    containTop: '', //顶部导航栏高度
    screenFixed: false, //筛选栏吸附
    showSearch1: true,
    searchid: '',
    // filterText: '',
    filterItems: [], // 筛选项
    filterIn: false, //显示筛选
    normalSearchList: [
      {
        key: '商品类型',

        stringList: [
          {
            label: '特卖',
            type: 'radio',
            value: 1,
            checked: false
          },
          {
            label: '常规',
            type: 'radio',
            value: 0,
            checked: false
          }
        ]
      }
    ],
    screenQuery: [],
    ruleDetail: null // 1 审核中 0 不审核
  },
  //输入搜索内容
  searchValue: function(e) {
    this.setData({
      searchText: e.detail.value
      // filterText: e.detail.value
    })
  },
  //取消
  cancel: function() {
    const that = this
    if (that.data.searchText) {
      that.setData({
        searchText: '',
        //  filterText: '',
        recordShow: true,
        SearchInfoShow: false
      })
      if (that.data.empty) {
        that.setData({
          empty: false
        })
      }
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
    that.setData({
      searchText: '',
      //  filterText: '',
      pageIndex: 1,
      pageSize: 20,
      sort: '',
      mallType: '',
      brand: '',
      priceState: 0, //搜索条件-价格状态
      discountState: 0, //搜索条件-折扣状态
      screeningState: 0, //搜索条件-筛选
      selected: []
    })
    this.getElementHeight()
  },
  //清空搜索内容\
  deleteInput: function() {
    this.setData({
      searchText: ''
      //  filterText: ''
    })
  },
  //搜索
  search: function() {
    const that = this
    if (that.data.searchText) {
      //将搜索内容存入搜索记录
      var history = wx.getStorageSync('historyList')
      if (!history) {
        history = []
      }
      history.unshift(that.data.searchText)

      history = ArrayToHeavy(history)
      that.setData({
        historyList: history,
        recordShow: false,
        SearchInfoShow: true,
        pageIndex: 1
      })
      that.getElementHeight()
      that.query()
      wx.setStorage({
        key: 'historyList',
        data: history
      })
    } else {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none',
        duration: 1500
      })
    }
  },
  //input框失焦
  blursearch: function(event) {
    const that = this

    that.setData({
      autoFocus: false
    })
  },
  //删除历史搜索记录
  deleteHistory: function() {
    const that = this
    that.setData({
      historyList: []
    })
    that.getElementHeight()
    wx.removeStorage({
      key: 'historyList',
      success(res) {}
    })
  },
  //读取历史搜索记录
  getHistory: function() {
    //读取搜索记录
    this.setData({
      historyList: wx.getStorageSync('historyList')
    })
  },
  //选中历史搜索记录
  selectHistoryItem: function(e) {
    const that = this
    const text = e.currentTarget.dataset.text
    that.setData({
      searchText: text
      //   filterText: text
    })
    that.search()
  },
  //选中热门搜索
  selectHotItem: function(e) {
    const that = this
    const searchName = e.currentTarget.dataset.searchname
    that.setData({
      searchText: searchName
      // filterText: searchName
    })
    that.search()
  },
  //搜索
  query: function(e) {
    const that = this
    const params = {
      q: that.data.searchText,
      screen: that.data.screenQuery,
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
      sort: that.data.sort,
      mallType: that.data.mallType,
      brand: that.data.brand
    }

    ModelSearch.q(params)
      .then(res => {
        let searchInfo = res.data
        wx.pageScrollTo({
          scrollTop: 0
        })
        //判断是否有下一页
        //判断搜索结果是否为空
        if (searchInfo.specialList.length == 0 && searchInfo.list.length == 0) {
          that.setData({
            empty: true,
            showSearch1: false
          })
        } else {
          that.setData({
            empty: false,
            showSearch1: true,
            SearchInfoShow: true
          })
        }
        //专场长度大于3，截取前三个，剩余的收缩
        if (searchInfo.specialList.length > 3) {
          searchInfo.showActivityList = []
          for (var i in searchInfo.specialList) {
            if (i <= 2) {
              searchInfo.showActivityList.push(searchInfo.specialList[i])
            }
          }
          that.setData({
            showMoreActivity: true
            //  searchInfo: searchInfo
          })
        } else {
          searchInfo.showActivityList = searchInfo.specialList
          that.setData({
            showMoreActivity: false
            //   searchInfo: searchInfo
          })
        }
        //从首页分类或者商品详情点击进来的情况
        if (that.data.type == 'click') {
          //是否为空判断
          if (searchInfo.list.length <= 0) {
            that.setData({
              empty: true
            })
          }
        }
        //筛选情况下
        // if(that.data.isBack){
        if (searchInfo.list.length <= 0) {
          that.setData({
            empty: true
          })
        }
        // }
        that.setData({
          isBack: false,
          screenFixed: false,
          searchInfo: searchInfo,
          hasNext: searchInfo.hasNext
        })
        //获取筛选栏距离顶部距离
        that.getScreenTop()
      })
      .catch()
  },
  //获取元素高度
  getElementHeight: function() {
    var query = wx.createSelectorQuery()
    //选择id
    var that = this
    query
      .select('.overList')
      .boundingClientRect(function(rect) {
        if (!rect) {
          return
        }
        const height = rect.height
        //  console.log('高度：'+height)
        if (height > 135) {
          that.setData({
            historyHeight: 130,
            isShowHistory: false,
            packUpHistory: false
          })
        } else {
          that.setData({
            isShowHistory: true
          })
        }
        //  console.log('是否下拉：'+that.data.isShowHistory)
        //  console.log('是否收起：'+that.data.packUpHistory)
      })
      .exec()
  },
  //下拉历史搜索记录
  dropDown: function() {
    this.setData({
      historyHeight: 260,
      isShowHistory: true,
      packUpHistory: true
    })
  },
  //收起历史搜索记录
  packUp: function() {
    this.setData({
      historyHeight: 130,
      isShowHistory: false,
      packUpHistory: false
    })
  },
  //展开更多会场
  tapToMoreActivity: function() {
    const that = this
    const searchInfo = that.data.searchInfo
    searchInfo.showActivityList = searchInfo.specialList
    that.setData({
      showMoreActivity: false,
      searchInfo: searchInfo
    })
    //获取筛选栏距离顶部距离
    that.getScreenTop()
  },
  //收起更多会场
  closeMoreActivity: function() {
    const that = this
    const searchInfo = that.data.searchInfo
    if (searchInfo.specialList.length > 3) {
      searchInfo.showActivityList = []
      for (var i in searchInfo.specialList) {
        if (i <= 2) {
          searchInfo.showActivityList.push(searchInfo.specialList[i])
        }
      }
      that.setData({
        hasNext: searchInfo.hasNext,
        showMoreActivity: true,
        searchInfo: searchInfo
      })
    }
    //获取筛选栏距离顶部距离
    that.getScreenTop()
  },
  // 去专场详情
  taoToActivity(e) {
    const specialCode = e.currentTarget.dataset.code
    wx.navigateTo({
      url: `/pages/activity/index?scode=${specialCode}`
    })
  },
  onLoad(options) {
    console.log('search onLoad==', options)
    // Do some initialize when page load.
    // 获取环境变量
    this.queryEnv()
    //检测是否是从首页分类和商品详情中跳转进来

    if (options.type == 'click') {
      //商品详情页跳过来只搜索品牌，搜索内容要为空
      if (options.brand) {
        this.setData({
          showSearch: false,
          recordShow: false,
          searchText: '',
          //  filterText: '',
          brand: options.brand
        })
        // 点击搜索框进入搜索条件
        this.normalSearchItems()
      } else {
        //首页进来只搜索内容，搜索品牌为空
        this.setData({
          showSearch: false,
          recordShow: false,
          searchText: options.searchText,
          //    filterText: options.searchText, //备份搜索分类关键字
          brand: '',
          searchid: options.searchid ? options.searchid : '' // 分类筛选项id，通过首页分类获取传到搜索页
        })
        // 20190425 首页顶部轮播跳转搜索页面后筛选项显示特卖常规
        if (options.normal == 1) {
          // 点击搜索框进入搜索条件
          this.normalSearchItems()
        } else {
          // 通过分类进入
          this.searchItems()
        }
      }
      this.setData({
        type: options.type
      })
      this.query()
    } else {
      //获取热门搜索
      this.getRecommend()
      //获取历史搜索记录
      this.getHistory()
      //获取元素高度
      this.getElementHeight()
      // 点击搜索框进入搜索条件
      this.normalSearchItems()
    }
    //获取筛选栏距离顶部距离
    this.getScreenTop()
  },
  // 获取环境变量`
  queryEnv() {
    let _this = this
    // 如果已经请求到了数据
    if (App.globalData.ruleDetail) {
      _this.setData({
        ruleDetail: App.globalData.ruleDetail
      })
      // 没有的话设置回调
    } else {
      App.queryEnvCb = res => {
        _this.setData({
          ruleDetail: res
        })
      }
    }
  },
  //价格筛选
  selectPrice: function() {
    const that = this
    var priceState = that.data.priceState
    var sort = that.data.sort
    if (priceState == 0) {
      priceState = 1
      sort = 'price-asc'
    } else if (priceState == 1) {
      priceState = 2
      sort = 'price-desc'
    } else if (priceState == 2) {
      priceState = 0
      sort = ''
    }
    that.setData({
      pageIndex: 1,
      priceState: priceState,
      discountState: 0,
      sort: sort
    })
    that.query()
  },
  //折扣筛选
  selectDiscount: function() {
    const that = this
    var discountState = that.data.discountState
    var sort = that.data.sort
    if (discountState == 0) {
      discountState = 1
      sort = 'discount-asc'
    } else if (discountState == 1) {
      discountState = 2
      sort = 'discount-desc'
    } else if (discountState == 2) {
      discountState = 0
      sort = ''
    }
    that.setData({
      pageIndex: 1,
      discountState: discountState,
      priceState: 0,
      sort: sort
    })
    that.query()
  },
  //筛选界面
  selectScreening: function() {
    // 筛选进入
    this.setData({
      filterIn: true
    })
  },
  //获取热门搜索
  getRecommend: function() {
    const that = this
    const params = {}
    ModelSearch.queryRecommend(params)
      .then(res => {
        that.setData({
          hotList: res.data.recommend
        })
      })
      .catch()
  },

  //获取筛选栏距离顶部的高度
  getScreenTop: function() {
    const that = this
    const contain = wx.createSelectorQuery()
    contain.select('.container').boundingClientRect()
    contain.exec(function(res) {
      that.setData({
        containTop: res[0].top
      })
    })
    if (that.data.SearchInfoShow) {
      const query = wx.createSelectorQuery()
      query.select('.goods-top').boundingClientRect()
      query.exec(function(res) {
        that.setData({
          fixTop: res[0].top - 44 - that.data.statusBarHeight
        })
      })
    }
  },
  // 常规搜索搜索选项
  normalSearchItems() {
    this.setData({
      searchItems: this.data.normalSearchList
    })
  },
  // 获取搜索关键词
  searchItems() {
    const _this = this
    ModelSearch.getSearchItems({
      bannerId: this.data.searchid
    }).then(res => {
      // 数据转换
      const searchItems = res.data.bannerScreen.map(n => {
        return Object.assign({}, n, {
          type: 'radio',
          key: n.screenKey,
          stringList: n.stringList.map((m, index) =>
            Object.assign(
              {},
              {
                checked: _this.data.filterItems.includes(m), // 回显query里有返回true
                value: m,
                label: m,
                id: index
              }
            )
          )
        })
      })
      this.setData({
        searchItems: searchItems
      })
    })
  },
  // 筛选
  doFilter(e) {
    const selected = e.detail
    // 如果是分类点击进入的筛选
    var screenArr = []
    var mallType = ''
    selected.map(m => {
      screenArr.push(encodeURIComponent(m.value))
      mallType = m.value
    })
    // 如果是分类点击进入的筛选
    if (this.data.searchid) {
      this.setData({
        selected: selected, // 筛选数组
        screenQuery: screenArr,
        pageIndex: 1,
        filterIn: false,
        screeningState: selected.length > 0 ? 1 : 0
      })
    } else {
      // 常规搜索筛选
      this.setData({
        selected: selected, // 筛选数组
        mallType: mallType,
        pageIndex: 1,
        filterIn: false,
        screeningState: selected.length > 0 ? 1 : 0
      })
    }

    this.query()
  },
  //删除筛选
  delete: function(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    let selected = that.data.selected
    selected.splice(index, 1)
    // 关键字重新拼接
    var screenArr = [] // 重新搜索关键词
    var searchArr = [] // 回显数据
    selected.map(m => {
      searchArr.push(m.value)
      screenArr.push(encodeURIComponent(m.value))
    })
    // 如果是分类点击进入的筛选
    if (this.data.searchid) {
      this.setData({
        screenQuery: screenArr
      })
    } else {
      // mallType 删除
      this.setData({
        mallType: ''
      })
    }
    this.setData({
      selected: selected, // 筛选数组
      pageIndex: 1,
      screeningState: selected.length > 0 ? 1 : 0
    })
    // 设置删除后的回显
    this.data.searchItems.map(n => {
      n.stringList.map((m, index) => {
        m.checked = searchArr.includes(m.value) // 回显query里有返回true
      })
    })
    this.setData({
      searchItems: this.data.searchItems
    })
    that.query()
  },
  onShow() {
    // Do something when page show.
    // console.log(this.data.selected)
    if (this.data.isBack) {
      this.query()
    }
  },

  onReachBottom() {
    // Do something when page reach bottom.
    this.data.pageIndex = this.data.pageIndex + 1
    this.loadMore()
  },

  //加载更多
  loadMore() {
    const that = this
    let searchInfo = that.data.searchInfo
    var empty = that.data.empty
    var showMoreActivity = that.data.showMoreActivity
    var showSearch1 = that.data.showSearch1
    if (this.data.loading || !this.data.hasNext) {
      return
    }
    const params = {
      q: that.data.searchText,
      screen: that.data.screenQuery,
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
      sort: that.data.sort,
      mallType: that.data.mallType,
      brand: that.data.brand
    }

    ModelSearch.q(params)
      .then(res => {
        //判断是否有下一页
        //判断搜索结果是否为空
        if (res.data.specialList.length == 0 && res.data.list.length == 0) {
          showSearch1 = false
          empty = true
        } else {
          showSearch1 = true
          empty = false
        }
        //专场长度大于3，截取前三个，剩余的收缩
        if (res.data.specialList.length > 3) {
          res.data.showActivityList = []
          for (var i in res.data.specialList) {
            if (i <= 2) {
              res.data.showActivityList.push(res.data.specialList[i])
            }
          }
          showMoreActivity = true
        } else {
          res.data.showActivityList = res.data.specialList
          showMoreActivity = false
        }
        searchInfo.showActivityList = res.data.showActivityList
        searchInfo.list = searchInfo.list.concat(res.data.list)
        that.setData({
          hasNext: res.data.hasNext,
          empty: empty,
          showMoreActivity: showMoreActivity,
          showSearch1: showSearch1,
          searchInfo: searchInfo
        })
      })
      .catch()
  },
  //页面滚动
  onPageScroll: function(e) {
    var that = this
    console.log('scroll：' + e.scrollTop);
    console.log('fixTop' + that.data.fixTop);
    if (e.scrollTop > that.data.fixTop) {
      if (e.scrollTop == 0) {
        that.setData({
          screenFixed: false
        })
      } else {
        that.setData({
          screenFixed: true
        })
      }
    } else {
      that.setData({
        screenFixed: false
      })
    }
    that.setData({
      scrollTop: e.scrollTop
    })
    console.log('scroll1：' + e.scrollTop);
    console.log('fixTop1' + that.data.fixTop);
  }
})
